package com.example.yunifang.myview;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;

/*
 * ScrollView骞舵病鏈夊疄鐜版粴鍔ㄧ洃鍚紝鎵�互鎴戜滑蹇呴』鑷瀹炵幇瀵筍crollView鐨勭洃鍚紝
 * 鎴戜滑寰堣嚜鐒剁殑鎯冲埌鍦╫nTouchEvent()鏂规硶涓疄鐜板婊氬姩Y杞磋繘琛岀洃鍚�
 * ScrollView鐨勬粴鍔╕鍊艰繘琛岀洃鍚�
 */
public class MyScrollView extends ScrollView {
	private OnScrollListener onScrollListener;  
    /** 
     * 涓昏鏄敤鍦ㄧ敤鎴锋墜鎸囩寮�yScrollView锛孧yScrollView杩樺湪缁х画婊戝姩锛屾垜浠敤鏉ヤ繚瀛榊鐨勮窛绂伙紝鐒跺悗鍋氭瘮杈�
     */  
    private int lastScrollY;
    
	public MyScrollView(Context context) {
		super(context, null);
	}
	public MyScrollView(Context context, AttributeSet attrs) {
		super(context, attrs, 0);
	}
	public MyScrollView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}
	/** 
     * 璁剧疆婊氬姩鎺ュ彛 
     * @param onScrollListener 
     */
	public void setOnScrollListener(OnScrollListener onScrollListener){
		this.onScrollListener = onScrollListener;
	}
	/** 
     * 鐢ㄤ簬鐢ㄦ埛鎵嬫寚绂诲紑MyScrollView鐨勬椂鍊欒幏鍙朚yScrollView婊氬姩鐨刌璺濈锛岀劧鍚庡洖璋冪粰onScroll鏂规硶涓�
     */  
    private Handler handler = new Handler() {  
  
        public void handleMessage(android.os.Message msg) {  
            int scrollY = MyScrollView.this.getScrollY();  
              
            //姝ゆ椂鐨勮窛绂诲拰璁板綍涓嬬殑璺濈涓嶇浉绛夛紝鍦ㄩ殧5姣缁檋andler鍙戦�娑堟伅  
            if(lastScrollY != scrollY){  
                lastScrollY = scrollY;  
                handler.sendMessageDelayed(handler.obtainMessage(), 5);    
            }  
            if(onScrollListener != null){  
                onScrollListener.onScroll(scrollY);  
            }  
              
        };  
  
    }; 
    /** 
     * 閲嶅啓onTouchEvent锛�褰撶敤鎴风殑鎵嬪湪MyScrollView涓婇潰鐨勬椂鍊欙紝 
     * 鐩存帴灏哅yScrollView婊戝姩鐨刌鏂瑰悜璺濈鍥炶皟缁檕nScroll鏂规硶涓紝褰撶敤鎴锋姮璧锋墜鐨勬椂鍊欙紝 
     * MyScrollView鍙兘杩樺湪婊戝姩锛屾墍浠ュ綋鐢ㄦ埛鎶捣鎵嬫垜浠殧5姣缁檋andler鍙戦�娑堟伅锛屽湪handler澶勭悊 
     * MyScrollView婊戝姩鐨勮窛绂�
     */ 
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		if(onScrollListener != null){  
            onScrollListener.onScroll(lastScrollY = this.getScrollY());  
        }  
        switch(ev.getAction()){  
        case MotionEvent.ACTION_UP:  
             handler.sendMessageDelayed(handler.obtainMessage(), 20);    
            break;  
        }  
		return super.onTouchEvent(ev);
	}

	/** 
     * 婊氬姩鐨勫洖璋冩帴鍙�
     */  
    public interface OnScrollListener{  
        /** 
         * 鍥炶皟鏂规硶锛�杩斿洖MyScrollView婊戝姩鐨刌鏂瑰悜璺濈 
         */  
        public void onScroll(int scrollY);  
    }
}
